//
//  StatusCell.swift
//  nimabi
//
//  Created by danny on 15/7/6.
//  Copyright © 2015年 DannyLiu. All rights reserved.
//

import UIKit
import FFAutoLayout
import SDWebImage

/// 图片视图可重用标示符
private let HMPictureCellReuseIdentifier = "HMPictureCellReuseIdentifier"

class StatusCell: UITableViewCell, UICollectionViewDataSource {

    /// 记录底部视图的约束,用来动态设置有图无图时,底部view 与 正文之间的约束
    var footerViewCons:NSLayoutConstraint?
    
    /// 配图视图宽度约束
    var widthCons: NSLayoutConstraint?
    /// 配图视图高度约束
    var heightCons: NSLayoutConstraint?
    
    ///  微博数据模型
    var status: Status? {
        
        didSet {
            // 头像
            iconView.sd_setImageWithURL(status?.user?.profileURL)
            // 认证图片
            vipIconView.image = status?.user?.verifiedImage
            memberIconView.image = status?.user?.mbrankImage
            
            nameLabel.text = status?.user?.name
            timeLabel.text = "刚刚"
            sourceLabel.text = "来自 微博nimei"
            contentLabel.text = status?.text
            
            // 计算图片视图的size
            let result = calcPictureViewSize(status!)
            
            
            // 设置图片视图的布局约束
            widthCons?.constant = result.viewSize.width
            heightCons?.constant = result.viewSize.height
            // 设置小格子的大小
            pictureLayout.itemSize = result.itemSize
          
            
            // 利用三目,无图时底部View与图片的距离为0,有图时设为12
            footerViewCons!.constant = result.viewSize == CGSizeZero ? 0 : 12
           
            
            // 重新刷新数据
            pictureView.reloadData()
            
        }
        
    }
    
    // MARK: collectionView的数据源方法
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return status?.imageURLs?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(HMPictureCellReuseIdentifier, forIndexPath: indexPath) as! StatusPictureCell
        
        // 赋值
        cell.imageURL = status!.imageURLs![indexPath.item]
        
        return cell
    }
    
    
    
    ///  根据微博模型计算图片是的大小
    /**
    0. 没有图片，返回zero
    1. 单图会按照图片等比例显示
    2. 多图的图片大小固定
    3. 多图如果是4张，会按照 2 * 2 显示
    4. 多图其他数量，按照 3 * 3 九宫格显示
    */
    private func calcPictureViewSize(status: Status) -> (viewSize:CGSize, itemSize:CGSize) {
        
        let itemSize = CGSize(width: 90, height: 90)
        let margin: CGFloat = 10
        // 获取图片的数量
        let count = status.imageURLs?.count
        
        // 0. 没有图片，返回zero
        if count == 0 {
            return (CGSizeZero, CGSizeZero)
        }
        
        // 1. 单图会按照图片等比例显示
        if count == 1 {
            // 1.1 从缓存拿到照片 
            // sdwebimage缓存图片文件名是对 url 的完整字符串 md5, 而我们取照片时用到的方法imageFromDiskCacheForKey(key)当中的key 指的是图片url的 完整字符串
            let key = status.imageURLs![0].absoluteString
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            
            return (image.size, image.size)
        }
        
        
        // 2. 多图的图片大小固定
        // 3. 多图如果是4张，会按照 2 * 2 显示
        if count == 4 {
            
            let w = itemSize.width * 2 + margin
            return (CGSize(width: w, height: w), itemSize)
            
        }
        
        // 4. 多图其他数量，按照 3 * 3 九宫格显示
        let rowCount = 3
        
        let row = (count! + 2) / rowCount as Int
        let w = itemSize.width * CGFloat(rowCount) + CGFloat(rowCount - 1) * margin
        let h = itemSize.height * CGFloat(row) + CGFloat(row - 1) * margin
        
        return (CGSize(width: w, height: h), itemSize)
        
    }
  
    
    // 在这个时候的frame 的宽是320,44 是iPhone5的 对6 和6+的尺寸是错误的(不要在这设置frame,但是可以设置自动布局)
    override  init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        // 获取屏幕的宽度
        let screenWidth = UIScreen.mainScreen().bounds.width
        
        // 添加顶部的分割视图
        let topView = UIView()
        addSubview(topView)
        topView.backgroundColor = UIColor(white: 0.5, alpha: 1.0)
        topView.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: CGSize(width: screenWidth, height: 10))
        
        addSubview(iconView)
        addSubview(nameLabel)
        addSubview(memberIconView)
        addSubview(vipIconView)
        addSubview(timeLabel)
        addSubview(sourceLabel)
        addSubview(contentLabel)
        addSubview(pictureView)
        pictureView.backgroundColor = UIColor(white: 1, alpha: 1)

        
        contentLabel.preferredMaxLayoutWidth = screenWidth - 12
 
        // 添加底部视图
        addSubview(footerView)
        footerView.backgroundColor = UIColor(white: 0.75, alpha: 1)

        // 准备配图视图
        preparePictureView()
        
        // 设置控件的自动布局
        
        iconView.ff_AlignVertical(ff_AlignType.BottomLeft, referView: topView, size: CGSize (width: 34, height: 34), offset: CGPoint(x: 12, y: 12))
        nameLabel.ff_AlignHorizontal(ff_AlignType.TopRight, referView: iconView, size: nil, offset: CGPoint(x: 12, y: 0))
        memberIconView.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: nameLabel, size: nil, offset: CGPoint(x: 12, y: 0))
        vipIconView.ff_AlignInner(ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: 8, y: 8))
        timeLabel.ff_AlignHorizontal(ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: 12, y: 0))
        sourceLabel.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: timeLabel, size: nil, offset: CGPoint(x: 12, y: 0))
        
        contentLabel.ff_AlignVertical(ff_AlignType.BottomLeft, referView: iconView, size: nil, offset: CGPoint(x: 0, y: 12))

//        addConstraint(NSLayoutConstraint(item: contentLabel, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.LessThanOrEqual, toItem: self, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: -12))
        
        
//        let cons = pictureView.ff_AlignVertical(ff_AlignType.BottomLeft, referView: contentLabel, size: CGSize(width: 290, height: 90), offset: CGPoint(x: 0, y: 12))
//
//        // 记录宽高的约束
//        widthCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Width)
//        heightCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Height)
        
        
        // 设置底部的视图的自动布局, 并记录下底部view的顶端与照片view的距离的约束
        let footCons = footerView.ff_AlignVertical(ff_AlignType.BottomLeft, referView: pictureView, size: CGSize(width: screenWidth, height: 44), offset: CGPoint(x: -12, y: 12))
        footerViewCons = footerView.ff_Constraint(footCons, attribute: NSLayoutAttribute.Top)
        
       
        // 这是最下面的 可以控制行高的布局
//        footerView.ff_AlignInner(ff_AlignType.BottomRight, referView: self, size: nil, offset: CGPoint(x: -8, y: -8))
        
    }
    
    ///  计算行高
    func rowHeight(status: Status) -> CGFloat {
        // 1 调用set方法,didSet方法
        self.status = status
        
        // 2 更新布局
        layoutIfNeeded()
        
        
        // 3 返回行高
        return CGRectGetMaxY(footerView.frame)

    }
    
    ///  准备配图视图
    private func preparePictureView() {
        
        // 1 数据源代理设置
        pictureView.dataSource = self
        // 2 注册可重用的cell
        pictureView.registerClass(StatusPictureCell.self, forCellWithReuseIdentifier: HMPictureCellReuseIdentifier)
        // 3 设置布局
        pictureLayout.minimumInteritemSpacing = 10
        pictureLayout.minimumLineSpacing = 10
        
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    // 懒加载控件
    lazy var iconView = UIImageView()
    
    lazy var nameLabel : UILabel = {
        
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(14)
        label.backgroundColor = UIColor.grayColor()
        
        return label
    }()
    
    lazy var memberIconView: UIImageView = UIImageView()
    lazy var vipIconView: UIImageView = UIImageView()
    
    lazy var timeLabel: UILabel = UILabel(color: UIColor.orangeColor(), fontSize: 10)
    lazy var sourceLabel: UILabel = UILabel (color: UIColor.darkGrayColor(), fontSize: 10)
    
    lazy var contentLabel: UILabel = UILabel (color: UIColor.darkGrayColor(), fontSize: 12, mutiLines: true)
   
    
    // 懒加载配图视图
    lazy var pictureLayout = UICollectionViewFlowLayout()
    lazy var pictureView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.pictureLayout)
    
    // 懒加载底部的footerView
    lazy var footerView: StatusFooterView = StatusFooterView()
    
}


///  自定义 配图cell
private class StatusPictureCell: UICollectionViewCell {
    
    /// 图像url地址
    var imageURL: NSURL? {
        didSet {
            iconView.sd_setImageWithURL(imageURL)
        }
        
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        // 设置图片的填充模式 而且还需要进行裁剪(在storyBoard中不需要裁剪)
        iconView.contentMode = UIViewContentMode.ScaleAspectFill
        iconView.clipsToBounds = true
        
        
        addSubview(iconView)
        ///  完全填充整个collectionView 的布局
        iconView.ff_Fill(self)
        
    }
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    lazy var iconView = UIImageView()
    
}


///  底部footerView
class StatusFooterView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(forwarBtn)
        addSubview(commentBtn)
        addSubview(likeBtn)
        
        // 设置布局, 水平平铺就可以了, 之间没有间距
        ff_HorizontalTile([forwarBtn, commentBtn, likeBtn], insets: UIEdgeInsetsZero)
        
        
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 懒加载按钮
    lazy var forwarBtn: UIButton = {
       let btn = UIButton()
        
        btn.setTitle("转发", forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "timeline_icon_retweet"), forState: UIControlState.Normal)
        
        btn.titleLabel?.font = UIFont.systemFontOfSize(12)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
        
        return btn
    }()
    
    lazy var commentBtn: UIButton = {
        let btn = UIButton()
        
        btn.setTitle("评论", forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "timeline_icon_comment"), forState: UIControlState.Normal)
        
        btn.titleLabel?.font = UIFont.systemFontOfSize(12)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
        
        return btn
        }()
    
    lazy var likeBtn: UIButton = {
        let btn = UIButton()
        
        btn.setTitle("点赞", forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "timeline_icon_unlike"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "timeline_icon_like"), forState: UIControlState.Selected)
        
        btn.titleLabel?.font = UIFont.systemFontOfSize(12)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
        
        return btn
        }()
    
}








